<template>
  <div>
    <div class="head" @click="goBack">
      <SvgIcon name="fanhui"></SvgIcon>
      <span>返回课程列表</span>
    </div>
    <a-tree
      v-model:selectedKeys="selectedKeys"
      :expandedKeys="expandedKeys"
      :treeData="treeData"
      :autoExpandParent="autoExpandParent"
      @expand="onExpand"
      @contextmenu.prevent="showContextMenu($event)"
      @select="onSelect"
    >
 
   
      <template #title="{ courseName, id, key }">
        <div v-if="editingKey === key" class="editable-title">
          <input v-model="editingTitle" @blur="saveEditing(key)" @keyup.enter="saveEditing(key)"   :ref="(el) => { if (el && editingKey === key) inputRef = el }"/>

        </div>
        <div v-else @dblclick="startEditing(key, courseName)">
          <div v-if="isRootKey(key)" @click="hideContextMenu" style="font-weight: 600;padding:10px 0;text-align:center;">
          <span style="margin-right: 8px;font-size:22px;">📚<span style="font-size:30px;">{{courseName}} </span></span>
 
       
        </div>
        <div v-else>
          <span style="margin-right: 8px">📒</span>
          {{courseName}}
         
        </div>
    
        </div>
      </template>
    </a-tree>
    <div
      v-if="showMenu"
      :style="{
        top: menuPosition.y + 'px',
        left: menuPosition.x + 'px',
      }"
      class="context-menu"
    >
      <ul>
        <li @click="addChapter">添加章节</li>
        <li @click="edits()" style="padding: 4px 8px; cursor: pointer">编辑</li>

        <li @click="del()" style="padding: 4px 8px; cursor: pointer">删除</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed, nextTick, onUnmounted } from 'vue';

  import { Tree, Button } from 'ant-design-vue';
  import SvgIcon from '@/components/Icon/src/SvgIcon.vue';
  import { edit, save, schoolCourseIdList } from '../SchoolCourse.api';
  //const editingKey = (ref < string) | (null > null);
  // const expandedKeys = ref(['1', '1-0', '1-1']);
  const editingTitle = ref('');
  const selectedKeys = ref(['']);
  // 当前选中的文件路径和内容
  const expandedKeys = ref([])
  const currentFileName = ref('');
  const currentFileContent = ref('');
  const editingKey = ref<string | null>(null);
  const inputRef = ref<HTMLInputElement | null>(null);
 
  const courseId = localStorage.getItem('schoolCourseId');
  onMounted(async() => {
   await getCourseList();
 

  });
  interface TreeNode {
    id: string;
    key: string;
    courseName: string;
    parentId?: string;
    courseDescribe?: string;
    isChildren?: boolean;
    children?: TreeNode[];
  }
  /*   const treeData = ref([
      {
        title: '人体动作识别课题',
        key: '1',
        children: [
          {
            title: '第一章：无标题文档',
            key: '1-0',
            children: [
              { title: '1. 什么是人体动作识别?', key: '1-0-0' },
              { title: '2. PoseC3D是如何工作的?', key: '1-0-1' },
              { title: '3. 关键技术介绍', key: '1-0-2' },
            ],
          },
          {
            title: '第二章：人体动作识别七步拆解',
            key: '1-1',
            children: [{ title: '1. 第一步通过Jupyter Notebook分步完成', key: '1-1-0' }],
          },
        ],
      },
    ]); */
  const treeData = ref<TreeNode[]>([]);
  const autoExpandParent = ref(true);
  const showMenu = ref(false);
  const currentNodeKey = ref(null);
  const menuPosition = ref({ x: 0, y: 0 });
  const emit = defineEmits(['coureName', 'selected-node','goback']);

  const onExpand = (expandedKeysValue) => {
    expandedKeys.value = expandedKeysValue;
    autoExpandParent.value = false;
  };
  
 

const isRootKey = (key: string) => {
  if (!treeData.value || treeData.value.length === 0) return false;
const rootNodes = treeData.value.filter((node)=>node.parentId==='0')
console.log(rootNodes,'topkeys')
return rootNodes.some(node => node.key === key);
 
};
  const getCourseList = async () => {
    console.log(courseId, 'courseId');
    try {
      const res = await schoolCourseIdList({ schoolCourseId: courseId });
      console.log(res, 'resschoolCourse');
      treeData.value = res;
       // 递归收集所有可展开节点的 key

 
    // 设置默认展开所有节点
    expandedKeys.value = collectExpandableKeys(treeData.value);
    
    } catch (error) {
      console.log('获取课程列表失败');
    }
  };
  const hideContextMenu = () => {
    showMenu.value = false;
  };
  const showContextMenu = (event) => {
    showMenu.value = true;
    console.log(event, 'event');
    const targetKey = selectedKeys.value[0];
    console.log('右键点击的节点 key:', targetKey);
    showMenu.value = true;
    menuPosition.value = { x: event.layerX, y: event.layerY };
    // isRootNode(targetKey) ? (chaptertitle.value = '添加章节') : (chaptertitle.value = '添加小节');
    //menuParent.value = parent;
    // 添加全局点击事件，点击其他地方时隐藏菜单
    // 假设右键当前选中的节点 // 记录右键点击的节点 key
    document.addEventListener('click', hideContextMenu);
  };
  const saveEditing = async (key) => {
    console.log('saveEditing');

    const newTitle = editingTitle.value.trim();
    console.log(newTitle, 'newTitle');
    if (!newTitle) {
      return;
    }
    // 找到要更新的节点
    const node = findNodeByKey(treeData.value, key);
    if (node) {
      // 更新节点的标题

      const parentNode = findParentNode(treeData.value, key);
      console.log(node, parentNode, 'nodeParentNODE');
      node.courseName = newTitle;
      emit('coureName', { courseName: newTitle, parentId: parentNode.id });
      //node.title = newTitle; // 确保同时更新 title 属性（如果适用）
    }

    // 更新本地树数据
    treeData.value = JSON.parse(JSON.stringify(treeData.value)); // 深拷贝触发响应式

    stopEditing();
  };
      const collectExpandableKeys = (nodes) => {
      let keys = [];
      for (const node of nodes) {
        if (node.children && node.children.length > 0) {
          keys.push(node.key);
          keys = keys.concat(collectExpandableKeys(node.children));
        }
      }
      return keys;
    };
  const findParentNode = (nodes, targetKey, parent = null) => {
    for (const node of nodes) {
      if (node.key === targetKey) {
        return parent; // 返回找到的父节点
      }
      if (node.children) {
        const foundParent = findParentNode(node.children, targetKey, node);
        if (foundParent) {
          return foundParent;
        }
      }
    }
    return null; // 如果没有找到父节点，返回 null
  };
  // 停止编辑
  const stopEditing = () => {
    editingKey.value = null;
    editingTitle.value = '';
  };
/*   const addChapter1 = () => {
    const targetKey = selectedKeys.value[0];
      // 递归添加章节并找到父节点
  let parentNode = null;

    const newChapter = {
      courseName: '新章节',
      key: `new-chapter-${Math.random().toString(36).substr(2, 9)}`,
      courseContent: '',
      id: `new-chapter-${Math.random().toString(36).substr(2, 9)}`,

      children: [],
    };
    newChapter.id = newChapter.key;
    // 递归添加章节

    const addChapterRecursively = (nodes) => {
      for (const node of nodes) {
        if (node.key === targetKey) {
          if (!node.children) {
            node.children = [];
          }

          node.children.push(newChapter);
          parentNode =node

          return true;
        }

        if (node.children && addChapterRecursively(node.children)) {
          return true;
        }
      }
      return false;
    };

    addChapterRecursively(treeData.value);

    treeData.value = JSON.parse(JSON.stringify(treeData.value));
     

  setTimeout(() => {
    startEditingAndFocus(newChapter.key, newChapter.courseName);
  }, 50);
    hideContextMenu();
  }; */
  const addChapter = () => {
  const targetKey = selectedKeys.value[0];
  if (!targetKey) return;

  // 查找父节点和要添加的新章节
  let parentNode = null;
  let parentKey = '';
  
  // 递归查找父节点
  const findParent = (nodes, key, currentParent = null) => {
    for (const node of nodes) {
      if (node.key === key) {
        parentNode = node;
        parentKey = currentParent?.key || '';
        return true;
      }
      if (node.children) {
        const found = findParent(node.children, key, node);
        if (found) return true;
      }
    }
    return false;
  };

  findParent(treeData.value, targetKey);

  if (!parentNode) return;

  // 创建新章节
  const newChapter = {
    courseName: '新章节',
    key: `new-chapter-${Math.random().toString(36).substr(2, 9)}`,
    courseContent: '',
    id: `new-chapter-${Math.random().toString(36).substr(2, 9)}`,
    parentId: parentNode.id,
    children: [],
  };
  newChapter.id = newChapter.key;

  // 添加新章节
  if (!parentNode.children) {
    parentNode.children = [];
  }
  parentNode.children.push(newChapter);

  // 更新树数据
  treeData.value = JSON.parse(JSON.stringify(treeData.value));

  // 确保父节点展开
  if (parentKey && !expandedKeys.value.includes(parentKey)) {
    expandedKeys.value = [...expandedKeys.value, parentKey];
  }

  // 延迟聚焦到新添加的章节输入框
  setTimeout(() => {
    startEditingAndFocus(newChapter.key, newChapter.courseName);
  }, 50);

  hideContextMenu();
};
  const edits = () => {
    const targetKey = selectedKeys.value[0];
    const node = findNodeByKey(treeData.value, targetKey);
    console.log(node, targetKey, 'node');
    if (node) {
      startEditing(targetKey, node.title);
    }
  };
  const findNodeByKey = (nodes, key) => {
    for (const node of nodes) {
      if (node.key === key) {
        return node;
      }
      if (node.children) {
        const foundNode = findNodeByKey(node.children, key);
        if (foundNode) {
          return foundNode;
        }
      }
    }
    return null;
  };
  // 新增一个专门处理编辑和焦点的方法
const startEditingAndFocus = (key, courseName) => {
  editingKey.value = key;
  editingTitle.value = courseName;
  
   nextTick(() => {
    if (inputRef.value) {
      inputRef.value.focus();
      inputRef.value.setSelectionRange(0, inputRef.value.value.length);
    }
  });
};
  const startEditing = (key, courseName) => {
    editingKey.value = key;

    editingTitle.value = courseName;

/*     nextTick(() => {
      if (inputRef.value) {
        inputRef.value.focus();

        inputRef.value.setSelectionRange(title.length, title.length);
      }
    }); */
     nextTick(() => {
    if (inputRef.value) {
      inputRef.value.focus();
      // 确保选择整个文本以便用户可以直接输入
      inputRef.value.setSelectionRange(0, inputRef.value.value.length);
    }
  });
  };

  const onSelect = async (selectedKeys, { node }) => {
    console.log(node, 'node111');
    selectedKeys.value = node.key;
    emit('selected-node', node);
  };

  const addSubNode = () => {
    const findNodeByKey = (nodes, key) => {
      for (const node of nodes) {
        if (node.key === key) {
          node.children.push({
            title: '新子节点',
            key: `new-sub-node-${Math.random().toString(36).substr(2, 9)}`,
          });
          return true;
        }
        if (node.children && findNodeByKey(node.children, key)) {
          return true;
        }
      }
      return false;
    };

    findNodeByKey(treeData.value, currentNodeKey.value);
    hideContextMenu();
  };

  const goBack = () => {
    console.log('返回课程列表');
    emit('goback')

  };
  // 初始化数据
  const initializeData = () => {
    treeData.value = [];
    selectedKeys.value = [''];
    editingKey.value = null;
    editingTitle.value = '';
    // 清空其他需要重置的状态
  };
  // 隐藏菜单点击其他地方
  onMounted(() => {
    document.addEventListener('click', hideContextMenu);
  });
  onUnmounted(() => {
    initializeData();
  });
</script>

<style scoped lang="less">
  .context-menu {
    position: absolute;
    background-color: white;
    border: 1px solid #ccc;
    z-index: 1000;
  }

  .context-menu ul {
    list-style: none;
    margin: 0;
    padding: 0;
  }

  .context-menu li {
    padding: 8px 12px;
    cursor: pointer;
  }

  .context-menu li:hover {
    background-color: #f0f0f0;
  }
  .head{
    margin-bottom: 20px;
    span{
      margin-left: 8px;
    }
  }
</style>
